//
// Created by gyc on 2023/5/11.
//
#include "../../common.h"

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        if (root == nullptr) {
            return root;
        }
        if (root->val == key) {
            if (root->left != nullptr && root->right != nullptr) {
                TreeNode *t = root->right;
                while (t->left != nullptr) {
                    t = t->left;
                }
                t->left = root->left;
                return root->right;
            } else if (root->left == nullptr) {
                return root->right;
            } else {
                return root->left;
            }
        }
        if (root->val > key) {
            root->left = deleteNode(root->left, key);
        } else {
            root->right = deleteNode(root->right, key);
        }
        return root;
    }
};